package com.ws.shop.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;

import com.ws.shop.bean.Page;
import com.ws.shop.dao.LinksDao;
import com.ws.shop.entity.Links;
@Repository(value="linksDao")
public class LinksDaoImpl extends BaseDaoImpl implements LinksDao{
	//获取数据
	final String findByPage_count = "select count(1) from jvf_links";
	final String findByPage_list = "select id,title,url,logo,state,ord from jvf_links";
	final String findByPage_order = " order by id";
	public Page findByPage(int pageno,int pagesize) {
		return findPage(pageno,pagesize,findByPage_count
				,new StringBuilder(findByPage_list).append(findByPage_order));
	}
	
	final String save_links = "insert into jvf_links(title,url,logo,state,ord) values(?,?,?,?,?)";
	final String update_links = "update jvf_links set title=?,url=?,logo=?,state=?,ord=? where id=?";
	public void saveOrUpdate(Links links) {
		if(links.getId() == 0)
			this.update(save_links, links.getTitle(),links.getUrl(),links.getLogo(),links.getState(),links.getOrd());
		else
			this.update(update_links, links.getTitle(),links.getUrl(),links.getLogo(),links.getState(),links.getOrd(),links.getId());
	}
	
	final String findLinksList_list = "select id,title,url,logo,state,ord from jvf_links";
	final String findLinksList_order = " order by ord";
	public List<Links> findLinksList(int state){
		StringBuilder query = new StringBuilder(" where 1=1");
		if(state >= 0){
			query.append(" and state=").append(state);
		}
		return this.query(new StringBuilder(findLinksList_list).append(query).append(findLinksList_order).toString(), new ResultSetExtractor<List<Links>>(){
			public List<Links> extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				List<Links> list = new LinkedList<Links>();
				Links ac = null;
				while(rs.next()){
					ac = new Links();
					ac.setId(rs.getInt(1));
					ac.setTitle(rs.getString(2));
					ac.setUrl(rs.getString(3));
					ac.setLogo(rs.getString(4));
					ac.setState(rs.getInt(5));
					ac.setOrd(rs.getInt(6));
					list.add(ac);
				}
				return list;
			}
		});
	}
	
	final String findLinksById = "select title,url ,logo,state,ord from jvf_links where id=?";
	public Links findLinksById(final int id) {
		return this.query(findLinksById, new ResultSetExtractor<Links>(){
			public Links extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				if(!rs.next())
					return null;
				Links l = new Links();
				l.setId(id);
				l.setTitle(rs.getString(1));
				l.setUrl(rs.getString(2));
				l.setLogo(rs.getString(3));
				l.setState(rs.getInt(4));
				l.setOrd(rs.getInt(5));
				return l;
			}
		} , id);
	}

}
